package com.fenghongzhang.day011;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.util.Log;

public class SMSOb extends ContentObserver {

    private ContentResolver contentResolver;

    private static final String TAG = "SMSOb";

    private Handler handler;
    public SMSOb(Handler handler,ContentResolver contentResolver) {
        super(handler);
        this.handler = handler;
        this.contentResolver = contentResolver;
    }

    /**
     * 让观察者,观察一个数据库, 一旦数据库的内容有变化,会自动调用onChange 方法
     * @param selfChange
     */
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
//        Log.i(TAG, "onChange: ");

        //在这里里面要取到新发来的短信的内容.
        Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);

        if(query!= null){
//            while(query.moveToNext()){
//                String s = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
//                Log.i(TAG, "onChange: "+s);
//            }
            //指向最新的条
            query.moveToFirst();
            String s = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
            Log.i(TAG, "onChange: "+s);

            Message obtain = Message.obtain();
            obtain.obj = s;

            handler.sendMessage(obtain);


            query.close();
        }

    }
}
